package com.zzyl.nursing.service.impl;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author alexis
 * @date 2025-10-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String,String > redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警过滤
     */
    @Override
    public void alertFilter() {
        //查询所有规则，遍历规则
        Long count = lambdaQuery().eq(AlertRule::getStatus, 1).count();
        if (count ==0  || count==null){
            log.info("没有启用的报警规则");
            return;
        }
        //从redis中查询所有上报的数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)){
            log.info("没有数据");
            return;
        }
        //数据格式标准化处理
        List<DeviceData> allDeviceDataList = new ArrayList<>();
        for (Object value : values){
            List<DeviceData> deviceDataList = JSONUtil.toList(value.toString(), DeviceData.class);
            allDeviceDataList.addAll(deviceDataList);
        }
        /**
         * 数据报警处理器
         */
        allDeviceDataList.forEach(this::alertFilter);
//        values.forEach(value -> {
//            List<AlertRule> alertRules = JSONUtil.toList(value.toString(), AlertRule.class);
//            allDeviceDataList.addAll(alertRules);
//        });



    }

    private void alertFilter(DeviceData deviceData) {
        //教验上报时间是否小于1分钟，如果大于1分钟，直接return
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60){
            return;
        }
        //准备当前上报产品物模型规则（查询当前设备的规则)
        List<AlertRule> currentIotRule = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId()).list();

        // 准备当前上报产品物模型规则（查询所有的设备的规则)
        List<AlertRule> allIotRule = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId,-1).list();
        //合并规则
        allIotRule.addAll(currentIotRule);
        if (CollUtil.isEmpty(allIotRule)){
            log.info("没有规则");
            return;
        }
        //遍历每一条规则
        allIotRule.forEach(alertRule -> {
            deviceDataAlarmHander(alertRule,deviceData);
        });
    }

    private void deviceDataAlarmHander(AlertRule alertRule, DeviceData deviceData) {
        //第一层校验-判断当前时间是否生效时间内
        String alertEffectivePeriod = alertRule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        if (LocalTime.now().isBefore(startTime) || LocalTime.now().isAfter(endTime)){
            log.info("当前时间不在生效时间段内");
            return;
        }


        //第二层校验-判断数据阈值（当前上报的数据，是否异常）
        String dataValue = deviceData.getDataValue();
        //获取规则中是阈值和运算符
        Double value = alertRule.getValue();
        String operator = alertRule.getOperator();
        //定义redis报警次数的key
        String alertTriggerCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX

                + ":"+alertRule.getFunctionId()
                +":" +alertRule.getId();
        //比较值dataValue和阈值value
        int compare = Double.compare(Double.parseDouble(dataValue), value);//0：相等 1：大于 2：小于
        if ( operator.equals(">=") && compare >= 0|| operator.equals("<") && compare < 0) {
            //满足阈值条件（说明数据异常）
            log.info("满足阈值条件上报数据值{}，运算符：{}，规则符{}", dataValue, operator, value);
        }else {
            //不满足阈值条件（说明数据正常）
            //删除redis报警次数 key：iot：+产品ID+功能ID+规则id value：1
            redisTemplate.delete(alertTriggerCountKey);
            return;
        }

        //第三层校验-判断当前设备是否处于沉默状态
        //拼接沉默周期的key
        String alertSilentKey = CacheConstants.ALERT_SILENT_PREFIX + ":" + alertRule.getFunctionId() + ":" + alertRule.getId();
        //从redis中获取沉默周期
        String silentValue = redisTemplate.opsForValue().get(alertSilentKey);
        if (StringUtils.isNotEmpty(silentValue)){
            log.info("当前设备处于沉默状态");
            return;
        }
        //第四层校验-判断持续周期
        //从redis中获取已报警次数
        String triggerCount = redisTemplate.opsForValue().get(alertTriggerCountKey);
        //计算当前报警次数
        Integer count = StrUtil.isEmpty(triggerCount) ? 1 : Integer.parseInt(triggerCount) + 1;
        //获取持续周期
        Integer duration = alertRule.getDuration();
        if (ObjectUtil.notEqual(count, duration)){
            log.info("当前设备处于持续周期内");
            redisTemplate.opsForValue().set(alertTriggerCountKey, count.toString());
            return;
        }

        //满足报警条件
        //删除redis报警次数 key：iot：+产品ID+功能ID+规则id value：1
        redisTemplate.delete(alertTriggerCountKey);
        //添加沉默周期
        redisTemplate.opsForValue().set(alertSilentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //查找报警通知人
        List<Long> userIds = new ArrayList<>();
        if (ObjectUtil.equals(alertRule.getAlertDataType(), 0)){
            //老人异常数据,通知护理员
            if (deviceData.getLocationType()==0){
                //说明是随身设备，根据位置类型，查询对应的护理员
                 userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            } else if (deviceData.getLocationType()==1&&deviceData.getPhysicalLocationType()==2){
                //说明是固定设备（床位），根据床位查老人，再根据老人查找护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }else {
            //设备异常数据，通知设备维修工
            userIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }

        //不论什么数据类型，都要通知超级管理员
        List<Long> longs = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");

        userIds.addAll(longs);
        //对用户id去重处理
//        userIds = userIds.stream().distinct().collect(Collectors.toList());
        userIds = CollUtil.distinct(userIds);

        //保存报警数据
        insertAlertData(userIds,deviceData,alertRule);


    }
@Autowired
private IAlertDataService alertDataService;
    private void insertAlertData(List<Long> userIds, DeviceData deviceData, AlertRule alertRule) {
        List<AlertData> alertDataList = userIds.stream().map(userId -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setAlertRuleId(alertRule.getId());
            alertData.setType(alertRule.getAlertDataType());
            alertData.setUserId(userId);
            alertData.setStatus(0);
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
            alertData.setAlertReason(alertReason);
            return alertData;
        }).collect(Collectors.toList());
        alertDataService.saveBatch(alertDataList);
    }
}


